<template>
  <div class="app-container">
    <el-form
      v-show="showSearch"
      ref="queryForm"
      size="small"
      :inline="true"
    >
      <el-form-item label="小区 / 楼栋" prop="communityAndbuilding">
        <el-cascader
          v-model="communityId"
          :options="Communities"
          :props="optionProps"
          clearable
          @change="treeSelectd"
        />
      </el-form-item>
      <el-form-item label="单元名称" prop="unitName">
        <el-input
          v-model="unitName"
          placeholder="请输入单元名称"
          maxlength="32"
          show-word-limit
          clearable
          @keyup.enter.native="getList"
        />
      </el-form-item>
      <el-form-item label="单元编码" prop="unitCode">
        <el-input
          v-model="unitCode"
          placeholder="请输入单元编码"
          maxlength="32"
          show-word-limit
          clearable
          @keyup.enter.native="getList"
        >
          <template slot="prepend">UNIT_</template>
        </el-input>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="getList"
        >搜索
        </el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置
        </el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate(multipleSelection[0])"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="delConfirm(ids)"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport()"
        >导出当前页
        </el-button>
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExportAll"
        >导出全部
        </el-button>
      </el-col>
      <right-toolbar
        :show-search.sync="showSearch"
        @queryTable="getList()"
      />
    </el-row>

    <el-table
      v-loading="loading"
      :data="Units"
      :row-key="Units.unitId"
      :default-expand-all="true"
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      @selection-change="handleSelectionChange"
    >
      <el-table-column
        type="selection"
        align="center"
        width="45"
      />
      <el-table-column
        width="50"
        label="序号"
        type="index"
        :index="indexMethod"
        align="center"
      />
      <el-table-column
        align="center"
        prop="unitName"
        label="单元名称"
        width="100"
      />
      <el-table-column
        align="center"
        prop="unitCode"
        label="单元编码"
        width="230"
      />
      <el-table-column
        align="center"
        prop="buildingName"
        label="楼栋"
        width="100"
      />
      <el-table-column
        align="center"
        prop="communityName"
        label="小区"
        width="150"
      />
      <el-table-column
        align="center"
        prop="unitLevel"
        label="层数"
        width="70"
      />
      <el-table-column
        align="center"
        prop="unitAcreage"
        label="建筑面积"
        width="100"
      />
      <el-table-column
        align="center"
        prop="unitHaveElevator"
        label="电梯"
        width="120"
      >
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.unitHaveElevator"
            style="display: block"
            active-text="有"
            inactive-text="无"
            active-value="1"
            inactive-value="0"
            @change="handleUpdateSwitch(scope.row)"
          />
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        prop="createTime"
        label="创建时间"
        width="150"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>

      <el-table-column
        align="center"
        prop="updateTime"
        label="修改时间"
        width="150"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.updateTime) }}</span>
        </template>
      </el-table-column>

      <el-table-column
        label="备注"
        align="center"
        prop="remark"
      ></el-table-column>
      <el-table-column
        fixed="right"
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        width="120"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >修改
          </el-button>

          <el-button
            v-if="scope.row.parentId !== 0"
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="delConfirm(scope.row)"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      :current-page.sync="curr"
      :page-sizes="[1, 5, 10, 20]"
      :page-size.sync="size"
      layout="total, sizes, prev, pager, next, jumper"
      :total.sync="total"
      @size-change="getList"
      @current-change="getList"
    />

    <!-- 添加或修改部门对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body @closed="cancel('formData')">
      <el-form ref="formData" :model="formData" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="选择小区" prop="communityId">
              <el-select v-model="formData.communityId" filterable placeholder="请选择" @change="loadBuilding">
                <el-option
                  v-for="item in Communities"
                  :key="item.communityId"
                  :label="item.communityName"
                  :value="item.communityId"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="选择楼栋" prop="buildingId">
              <el-select v-model="formData.buildingId" filterable placeholder="请选择" clearable>
                <el-option
                  v-for="item in Buildings"
                  :key="item.buildingId"
                  :label="item.buildingName"
                  :value="item.buildingId"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="单元名称" prop="formData.unitName">
              <el-input v-model="formData.unitName" placeholder="单元名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="建筑面积" prop="formData.unitAcreage">
              <el-input-number
                v-model="formData.unitAcreage"
                controls-position="right"
                :min="1"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="层数" prop="formData.unitLevel">
              <el-input-number
                v-model="formData.unitLevel"
                controls-position="right"
                :min="1"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="电梯" prop="formData.unitHaveElevator">
              <el-switch
                v-model="formData.unitHaveElevator"
                active-text="有"
                inactive-text="无"
                active-value="1"
                inactive-value="0"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col>
            <el-form-item label="备注" prop="formData.remark">
              <el-input
                v-model="formData.remark"
                type="textarea"
                placeholder="请输入备注"
                clearable
                minlength="5"
                maxlength="128"
                show-word-limit
                rows="4"
              />
            </el-form-item>
          </el-col>
        </el-row>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel('formData')">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
// 时间转换类
import { parseTime } from '@/utils'
// 增删查改的请求
import {
  resultResolve,
  addUnit,
  updateUnit,
  deleteUnit,
  listUnit,
  listAllCommunity,
  listAllBuilding
} from '@/api/community'
// 登录信息
import store from '@/store'
import { getToken } from '@/utils/auth'

export default {
  name: 'Index',
  data() {
    return {
      // 加载层
      loading: true,
      // 多选中id数组
      ids: [],
      // 单元数据集合
      Units: [],
      // 小区下拉框
      Communities: [],
      Buildings: [],
      // 多选集合
      multipleSelection: [],
      // 小区、楼栋
      communityAndbuilding: [],
      // 多选禁用
      multiple: true,
      // 单选禁用
      single: true,
      // 搜索表单展示
      showSearch: true,
      // 表单验证规则
      rules: {},
      // 模糊查询单元编码
      unitCode: '',
      // 模糊查询单元名称
      unitName: '',
      // 小区id
      communityId: '',
      // 楼栋id
      buildingId: '',
      // 分页初始页
      curr: 1,
      // 分页大小
      size: 10,
      // 分页数据总条数
      total: 10,
      // 表单弹出层标题
      title: '添加单元',
      // 弹出层默认隐藏
      open: false,
      // 默认表单为新增
      isAdd: true,
      // 表单数据
      formData: {
        buildingId: '',
        communityId: '',
        unitName: '',
        unitAcreage: '',
        unitLevel: '',
        unitHaveElevator: '',
        remark: '',
        createBy: '',
        updateBy: ''
      },
      optionProps: {
        checkStrictly: true,
        lazy: true,
        leaf: 'buildName',
        expandTrigger: 'hover',
        lazyLoad: async(node, resolve) => {
          const param = node.value || 0
          const res = await listAllBuilding(param)
          const nodes = res.data.map(e => ({ communityId: e.buildingId, communityName: e.buildingName, leaf: true }))
          resolve(nodes)
        },
        value: 'communityId',
        label: 'communityName'
      }
    }
  },
  created() {
    this.getList()
    this.loadCommunities()
  },
  methods: {
    // 异步查询单元数据
    async getList() {
      this.loading = true
      const param = {
        'curr': this.curr,
        'size': this.size,
        'unitCode': this.unitCode,
        'unitName': this.unitName,
        'buildingId': this.buildingId,
        'communityId': this.communityId
      }
      const res = await listUnit(param)
      this.Units = res.data.records
      this.total = res.data.total
      this.loading = false
    },
    // 点击新增按钮开启弹窗
    handleAdd() {
      this.isAdd = true
      this.title = '添加单元'
      this.open = true
    },
    // 点击修改回填数据开启弹窗
    async handleUpdate(row) {
      this.isAdd = false
      this.title = '修改单元'
      this.open = true
      this.formData = JSON.parse(JSON.stringify(row))
      const res = await listAllBuilding(this.formData.communityId)
      this.Buildings = res.data
    },
    // 多选状态改变
    handleSelectionChange(val) {
      this.multipleSelection = val
      this.ids = val.map(data => data.unitId)
      this.single = val.length !== 1
      this.multiple = !val.length
    },
    // 重置查询
    resetQuery() {
      this.unitName = ''
      this.unitCode = ''
      this.communityId = ''
      this.buildingId = ''
      this.curr = 1
      this.size = 10
      this.getList()
    },
    // 删除确认
    delConfirm(row) {
      const param = row.unitId || this.ids
      this.$confirm('此操作将永久删除选中的' + param + '数据, 是否继续?', '删除提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.handleDelete(param)
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 删除方法
    async handleDelete(param) {
      const res = await deleteUnit(param)
      // 处理结果（响应弹窗）
      resultResolve(res, this)
    },
    // 提交新增/修改数据
    async submitForm() {
      let res = ''
      if (this.isAdd) {
        this.formData.createBy = store.getters.name
        res = await addUnit(this.formData)
      } else {
        this.formData.updateBy = store.getters.name
        res = await updateUnit(this.formData)
      }
      resultResolve(res, this)
      this.cancel()
    },
    // 电梯状态
    async handleUpdateSwitch(row) {
      let res = await updateUnit(row)
      resultResolve(res, this)
    },
    // 取消/关闭弹出层清空表单
    cancel(formName) {
      this.open = false
      this.formData = {
        communityId: '',
        buildingId: '',
        unitName: '',
        unitAcreage: '',
        remark: '',
        createBy: '',
        updateBy: ''
      }
    },
    // 导出当页数据
    handleExport() {
      const param = {
        'curr': this.curr,
        'size': this.size,
        'unitCode': this.unitCode,
        'unitName': this.unitName,
        'buildingId': this.buildingId,
        'communityId': this.communityId,
        'Authorization': getToken()
      }
      location.href = 'http://localhost:8080/zyUnit/export?' + this.qs.stringify(param)
    },
    // 导出全部数据
    handleExportAll() {
      const param = {
        'curr': 1,
        'size': this.total,
        'Authorization': getToken()
      }
      location.href = 'http://localhost:8080/zyUnit/export?' + this.qs.stringify(param)
    },
    // 时间格式化
    parseTime(time) {
      return parseTime(Date.parse(time))
    },
    // 修改序号
    indexMethod(index) {
      index = (index + 1) + (this.curr - 1) * this.size
      return index
    },
    async loadCommunities() {
      const res = await listAllCommunity()
      this.Communities = res.data
    },
    treeSelectd(node) {
      if (node.length > 1) {
        this.communityId = node[0]
        this.buildingId = node[1]
      } else {
        this.communityId = node[0]
        this.buildingId = ''
      }
      this.getList()
    },
    async loadBuilding(node) {
      this.formData.buildingId = ''
      const res = await listAllBuilding(node)
      this.Buildings = res.data
    }
  }
}
</script>

